<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;

class userController extends Controller
{
    // 登录
    public function login(Request $request)
    {
        // 判断是否已经登录
        if ($request->session()->has('uEmail')) {
            // echo '<script type = "text/javascript">alert("请勿重复登录");</script>';
            return redirect()->route('home');
        }

        // 判断是否经过login
        if ($_SERVER["HTTP_REFERER"] != env('APP_URL').'/login'){
            return view('login', ['title'=>'登录']);
        }

        // 接收前端传过来的参数
        $uEmail = $_POST['email']??'e@mail.com';
        $uPwd = $_POST['pwd']??'passwd';

        // 查询数据库
        $users = DB::table('users')->where('uemail', $uEmail)->first();
        // $users = DB::select('select * from user where uemail = ?', [$uEmail]);

        // 判断数据
        if ($users == NULL){
            return response('错误的用户或密码')->header('refresh', env('USER_WAIT', '5').';url='.env('APP_URL'));
        }elseif ($uPwd == $users->upasswd){
            // 注册session变量
            session(['uId' => $users->uid]);
            session(['uName' => $users->uname]);
            session(['uEmail' => $users->uemail]);

            DB::table('logs')->insert([
                'cid' => '0',
                'uid' => $users->uid,
                'operate' => '登录',
                'date' => time()
            ]);

            // $data = $request->session()->all();
            // return response(dump($request->session()->all()));

            return redirect()->route('home');
        }else {
            return response('错误的用户或密码')->header('refresh', env('USER_WAIT', '5').';url='.env('APP_URL'));
        }

        // if ($users){
        //     if ($users->upasswd == $uPwd) {
        //         // echo '<script type = "text/javascript">alert("登陆成功");</script>';
        //         // 注册session变量
        //         // session(['loginCheck' => 'true']);
        //         session(['uId' => $users->uid]);
        //         session(['uName' => $users->uname]);
        //         session(['uEmail' => $users->uEmail]);
        //         $data = $request->session()->all();
        //         // return view('home');
        //         // return response($data);
        //         // $request->session()->all();
                
        //         // return redirect()->route('home');
        //     }
        // }else {
        //     // echo '<script type = "text/javascript">alert("此账户不存在");</script>';
        //     // return view('login');
        //     return redirect()->route('home');
        // }
    }

    // 登出
    public function logout(Request $request)
    {
        // 登录验证
        if ($request->session()->has('uEmail')) {
            DB::table('logs')->insert([
                'cid' => '0',
                'uid' => session('uId')??'0',
                'operate' => '登出',
                'atitle' => '',
                'date' => time()
            ]);
            $request->session()->forget('uId');
            $request->session()->forget('uName');
            $request->session()->forget('uEmail');
            // $request->session()->flush();
            return redirect()->back();
        }else {
            return redirect()->route('home');
        }
    }

    // 博客管理页
    public function admin($id = NULL)
    {
        if (session('uEmail', 'null') == 'null') {
            return response('你还没有登录')->header('refresh', env('USER_WAIT', '5').';url='.env('APP_URL'));
        }
        // return response($id.'管理页面');
        $logs = DB::table('logs')->orderBy('lid', 'desc')->limit(6)->get();
        return view('admin', ['id'=>$id, 'title'=>'博客后台管理系统', 'logs'=>$logs]);
    }

    // 更改密码
    public function updatepwd(Request $request)
    {
        // 判断是否已经登录
        if (!$request->session()->has('uEmail')) {
            return redirect()->route('login');
        }
        // 判断是否经过login
        // if ($_SERVER['HTTP_REFERER'] != $_SERVER['HTTP_HOST'].'/updatepwd'){
        if ((url()->previous()) != env('APP_URL').'/updatepwd'){            
            // return redirect()->route('updatepwd');
            // $str = env('APP_URL').'/updatepwd';
            // return response($str);
            return view('admin.updatapwd', ['title'=>'修改密码']);
        }
        // 接收前端传过来的参数
        $uEmail = $_POST['uEmail']??session('uEmail');
        $uOldPwd = $_POST['uOldPwd']??'passwd';
        $uNewPwd = $_POST['uNewPwd']??$uOldPwd;

        $data = DB::table('users')->where('uemail', $uEmail)->first();

        if ($data == NULL){
            return response('你没有登录')->header('refresh', env('USER_WAIT', '5').';url='.env('APP_URL'));
        }elseif ($uOldPwd == $uNewPwd){
            return response('新旧密码一致')->header('refresh', env('USER_WAIT', '5').';url='.env('APP_URL'));
        }elseif ($uEmail == $data->uemail){
            $update = DB::table('users')->where('uemail', $uEmail)->update(['upasswd'=>$uNewPwd]);
            if ($update) {
                DB::table('logs')->insert([
                    'cid' => '0',
                    'uid' => session('uId')??'0',
                    'operate' => '修改',
                    'atitle' => '密码',
                    'date' => time()
                ]);
                $request->session()->forget('uId');
                $request->session()->forget('uName');
                $request->session()->forget('uEmail');
                // $request->session()->forget('check');
                return response('修改成功，请重新登录')->header('refresh', env('USER_WAIT', '5').';url='.env('APP_URL'));
            }else {
                return response('修改失败')->header('refresh', env('USER_WAIT', '5').';url='.env('APP_URL'));
            }
        }else {
            return response('未知错误')->header('refresh', env('USER_WAIT', '5').';url='.env('APP_URL'));
        }
        // $data = DB::select('select * from user where uemail = ?', [$uEmail]);
        // return view('admin.updatepwd');
        // return view('debug', ['data'=>$data]);
    }
}